import { Injectable, Logger } from "@nestjs/common";
import { TombService } from "../services/tomb.service";

// 说明：该处理器为文档中挖宝流程提供WS分发表实现骨架。
// 实际坑位状态、道具库存、中奖逻辑与历史记录应落在相应的表与服务中。

@Injectable()
export class TombWsHandlers {
  private readonly logger = new Logger(TombWsHandlers.name);

  constructor(private readonly tombService: TombService) {}

  /** 1591: 查询探穴次数/坑洞状态 */
  async handleQueryPits(payload: any, helpers: any) {
    const characterId = helpers.selectedCharacterId;
    if (!characterId) {
      return { act_id: 1591, code: -1, msg: "请先选择角色" };
    }
    const dateStr = this.todayStr();
    try {
      const res = await this.tombService.queryPits(characterId, dateStr);
      return {
        act_id: 1591,
        code: 0,
        data: res.pits.map((p) => [p.state, p.pitId]),
        limit: res.limit,
      };
    } catch (error: any) {
      return { act_id: 1591, code: -1, msg: error?.message || "查询失败" };
    }
  }

  /** 1412: 购买洛阳铲 */
  async handleBuyShovel(payload: any, helpers: any) {
    const characterId = helpers.selectedCharacterId;
    if (!characterId) {
      return { act_id: 1412, code: -1, msg: "请先选择角色" };
    }
    const count = Number(payload?.c ?? 0);
    const dateStr = this.todayStr();
    try {
      if (count > 0) {
        // 购买并返回“剩余挖宝次数”
        const res = await this.tombService.buyShovel(
          characterId,
          dateStr,
          count
        );
        return {
          act_id: 1412,
          code: 0,
          data: [0, res.timesAfter, 0],
          msg: "您成功购买了一把洛阳铲，获得了 100 次探穴机会",
        };
      }
      // c=0 时：仅查询剩余挖宝次数，返回 [0, remain, 0]
      const remain = await this.tombService.getRemainShovel(
        characterId,
        dateStr
      );
      return { act_id: 1412, code: 0, data: [0, remain, 0] };
    } catch (error: any) {
      return { act_id: 1412, code: -1, msg: error?.message || "处理失败" };
    }
  }

  /** 1411: 挖宝 */
  async handleDig(payload: any, helpers: any) {
    const characterId = helpers.selectedCharacterId;
    if (!characterId) {
      return { act_id: 1411, code: -1, msg: "请先选择角色" };
    }
    const pitId = Number(payload?.i || 0);
    if (!pitId) return { act_id: 1411, code: -1, msg: "坑位无效" };
    const today = this.todayStr();
    try {
      const r = await this.tombService.dig(characterId, pitId, today);
      // 挖到珍矿宝盒：按赌场广播格式推送，内容格式要求
      try {
        if (r.rewardType === 5 && /珍矿宝盒/.test(r.rewardDesc || "")) {
          const now = new Date();
          const hh = String(now.getHours()).padStart(2, "0");
          const mm = String(now.getMinutes()).padStart(2, "0");
          const role = await helpers.characterService.getCharacterById(
            characterId
          );
          const roleName = role?.name || `角色${characterId}`;
          const desc = `恭喜${roleName}(${characterId})在宝洞中挖到珍矿宝盒！`;
          const broadcastMessage = {
            act_id: 260,
            code: 0,
            data: {
              c: desc,
              h: `${hh}:${mm}`,
              id: characterId,
              n: "系统",
              rid: 1000,
              t: 6,
            },
          };
          await helpers.systemMessageService.saveChibiResultMessage(
            broadcastMessage,
            0
          );
          await helpers.redisService.publish(
            "casino.chibi.result",
            JSON.stringify(broadcastMessage)
          );
        }
      } catch (_) {}
      // 每次挖完后，附带一次 1591 的当前页面信息
      const q = await this.tombService.queryPits(characterId, today);
      return {
        act_id: 1411,
        code: 0,
        data: [r.pageIdxOrCode, r.resultType, r.timesLeft],
        msg: r.message,
        extra: {
          act_id: 1591,
          code: 0,
          data: q.pits.map((p) => [p.state, p.pitId]),
          limit: q.limit,
        },
      };
    } catch (error: any) {
      const msg = error?.message || "挖掘失败";
      if (msg.includes("上限") || msg.includes("不足")) {
        return { act_id: 1411, code: 8, msg };
      }
      return { act_id: 1411, code: -1, msg };
    }
  }

  /** 1592: 中奖动态 */
  async handleHistory(payload: any, helpers: any) {
    try {
      const rows = await this.tombService.historyRecent(50);
      // 替换 n 为角色名
      const result = await Promise.all(
        rows.map(async (r) => {
          const name =
            (await helpers.characterService.getCharacterById(r.id))?.name ||
            `角色${r.id}`;
          return { ...r, n: name };
        })
      );
      return { act_id: 1592, code: 0, data: result };
    } catch (error: any) {
      return { act_id: 1592, code: -1, msg: error?.message || "查询失败" };
    }
  }

  private todayStr(): string {
    const now = new Date();
    const y = now.getFullYear();
    const m = String(now.getMonth() + 1).padStart(2, "0");
    const d = String(now.getDate()).padStart(2, "0");
    return `${y}-${m}-${d}`;
  }

  // 奖励逻辑由服务内实现
}
